package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.Role;

import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.List;

/**
 * 用户管理控制层
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @Autowired
    private JedisPool jedisPool;

    /**
     * 获取用户名 从SecurityContextHolder获取用户数据
     * @return
     */
    @RequestMapping(value = "/getUserName", method = RequestMethod.GET)
    public Result getUserName() {
        try {
            User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return new Result(true, MessageConstant.GET_USERNAME_SUCCESS,user.getUsername());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_USERNAME_FAIL);
        }
    }

    /**
     * 用户分页查询
     */
    @RequestMapping(value = "/findPage", method = RequestMethod.POST)
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean) {
        PageResult pageResult = userService.findPage(queryPageBean.getCurrentPage(), queryPageBean.getPageSize(), queryPageBean.getQueryString());
        return pageResult;
    }

    /**
     *所有角色查询
     */
    @RequestMapping(value = "/findAll", method = RequestMethod.POST)
    public Result findAll() {
        try {
            List<Role> roleList = userService.findAll();
            return new Result(true, MessageConstant.QUERY_ROLE1_SUCCESS,roleList);
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ROLE1_FAIL);
        }
    }

    /**
     * 新增用户
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public Result add(@RequestBody com.itheima.pojo.User user, Integer[] roleIds) {
        try {
            Jedis jedis = jedisPool.getResource();
            jedis.select(3);
            jedis.flushDB();
            String password = user.getPassword();
            String newPassword = getNewPassword(password);
            user.setPassword(newPassword);
            userService.add(user,roleIds);
            return new Result(true, MessageConstant.ADD_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ADD_USER_FAIL);
        }
    }

    /**
     * 转换密文方法
     * @param password
     * @return
     */
    private String getNewPassword(String password) {
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        String newPassword = bCryptPasswordEncoder.encode(password);
        return newPassword;
    }


    /**
     * 根据用户id删除用户信息
     */
    @RequestMapping(value = "/deleteById", method = RequestMethod.GET)
    public Result deleteById(Integer id) {
        try {
            Jedis jedis = jedisPool.getResource();
            jedis.select(3);
            jedis.flushDB();
            userService.deleteById(id);
            return new Result(true, MessageConstant.DELETE_USER_SUCCESS);
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false, e.getMessage());
        }catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.DELETE_USER_FAIL);
        }
    }

    /**
     * 根据用户id 回显用户列表
     */
    @RequestMapping(value = "/findById", method = RequestMethod.GET)
    public Result findById(Integer userId) {
        try {
            com.itheima.pojo.User user = userService.findById(userId);
            return new Result(true, MessageConstant.QUERY_USER_SUCCESS,user);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_USER_FAIL);
        }
    }

    /**
     * 根据用户id 查询角色ids
     */
    @RequestMapping(value = "/findRoleIdsByUserId", method = RequestMethod.GET)
    public List<Integer> findRoleIdsByUserId(Integer userId) {
        return userService.findRoleIdsByUserId(userId);
    }

    /**
     * 编辑用户
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST)
    public Result edit(@RequestBody com.itheima.pojo.User user, Integer[] roleIds) {
        try {
            Jedis jedis = jedisPool.getResource();
            jedis.select(3);
            jedis.flushDB();
            userService.edit(user,roleIds);
            return new Result(true, MessageConstant.EDIT_USER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EDIT_USER_FAIL);
        }
    }

    /**
     * 密码修改
     */
    @RequestMapping(value = "/upPassword", method = RequestMethod.POST)
    public Result upPassword(@RequestBody com.itheima.pojo.User user, Integer password) {
        try {
            //int类型需要转成字符串
           String password1 =password+"";
           //调用方法:明文转换诚密文
            String password2 = getNewPassword(password1);
            //需要用到用户的id
            userService.upPassword(user.getId(),password2);
            return new Result(true, MessageConstant.ALTER_PASSWORD_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ALTER_PASSWORD_FAIL);
        }
    }

    /**
     * 查询所有的用户
     */
    @RequestMapping(value = "/findUsers",method = RequestMethod.GET)
    public List findUsers(){
        try {
            List<com.itheima.pojo.User> users = userService.findUsers();
            return users;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

}
